package com.example.shortlink.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.shortlink.common.biz.user.UserContext;
import com.example.shortlink.common.convention.exception.ServiceException;
import com.example.shortlink.common.convention.result.Result;
import com.example.shortlink.dao.entity.TGroup;
import com.example.shortlink.dao.mapper.TGroupMapper;
import com.example.shortlink.remote.ShortLinkRemoteService;
import com.example.shortlink.remote.dto.req.ShortLinkRecycleBinPageReqDTO;
import com.example.shortlink.remote.dto.resp.ShortLinkPageRespDTO;
import com.example.shortlink.service.RecycleBinService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.example.shortlink.dao.entity.table.TGroupTableDef.T_GROUP;

/**
 * URL 回收站接口实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RecycleBinServiceImpl implements RecycleBinService {

    private final TGroupMapper groupMapper;

    /**
     * 后续重构为 SpringCloud Feign 调用
     */
    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };

    @Override
    public Result<Page<ShortLinkPageRespDTO>> pageRecycleBinShortLink(ShortLinkRecycleBinPageReqDTO requestParam) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(T_GROUP.DEFAULT_COLUMNS)
                .from(T_GROUP)
                .where(T_GROUP.USERNAME.eq(UserContext.getUsername())
                        .and(T_GROUP.DEL_FLAG.eq(Boolean.FALSE)));
        List<TGroup> groupList = groupMapper.selectListByQuery(queryWrapper);
        if (CollUtil.isEmpty(groupList)) {
            throw new ServiceException("用户无分组信息");
        }
        requestParam.setGidList(groupList.stream().map(TGroup::getGid).toList());
        return shortLinkRemoteService.pageRecycleBinShortLink(requestParam);
    }
}
